import { useAuthStore } from '@/stores/user'

const hasPermission = (str) => {
  const store = useAuthStore()
  let permission = store.user.permission || []
  let vl = false

  if (typeof str == 'string' && permission.indexOf(str) != -1) {
    vl = true
  } else {
    for (const s of str) {
      if (permission.indexOf(s) != -1) {
        vl = true
        break
      }
    }
  }
  return vl
}

const isAuthDirective = {
  mounted(el, binding) {
    const btnCodes = binding.value
    const isAuth = hasPermission(btnCodes)

    if (!isAuth) {
      el.parentNode?.removeChild(el)
    }
  }
}

export default {
  install(app) {
    app.directive('has', isAuthDirective)
  }
}
